package com.taiyuan.zfmvp.controller;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Util {
	/**
	* 利用java原生的摘要实现SHA256加密
	* @param str 加密后的报文
	* @return
	*/
	public static String getSHA256StrJava(String str){
		MessageDigest messageDigest;
		String encodeStr = "";
		try {
		messageDigest = MessageDigest.getInstance("SHA-256");
		messageDigest.update(str.getBytes("UTF-8"));
		encodeStr = byte2Hex(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeStr;
	}
	/**
	* 将byte转为16进制
	* @param bytes
	* @return
	*/
	private static String byte2Hex(byte[] bytes){
		StringBuffer stringBuffer = new StringBuffer();
		String temp = null;
		for (int i=0;i<bytes.length;i++){
		temp = Integer.toHexString(bytes[i] & 0xFF);
		if (temp.length()==1){
		//1得到一位的进行补0操作
		stringBuffer.append("0");
		}
		stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}

	public static void main(String[] args) {
		String str = getSHA256StrJava("{\"externalOrderId\":\"164528450271712\",\"checkId\":\"11202202241496781873414012928\",\"phone\":\"\",\"name\":\"肖莉\",\"idCard\":\"513030200305082826\",\"receiver\":\"肖莉\",\"linkPhone\":\"13219411628\",\"province\":\"四川\",\"city\":\"达州市\",\"county\":\"渠县\",\"detailAddress\":\"渠光路194号渠县职业中专学校肖莉\",\"price\":\"0\",\"channelId\":\"10731\",\"sceneId\":\"1442\", \t\"subScene\":\"\" }"+"95c8fa367ea643bfa2239a5a081e0e81");

		System.out.println(str);
	}
}
